//
// Created by LiuYou on 2021/8/19.
//

#include <csignal>
#include <fcntl.h>
#include "ProcessPool.hpp"

Process::Process() : pid( -1 ), pipeFd() {}

Process::~Process() = default;

/*static*/ int setFdNonblocking(int fd) {
    int oldOption = fcntl( fd, F_GETFL );
    // 疑惑解开, 将文件描述符设置为非阻塞, 使用的是宏 O_NONBLOCK。
    int newOption = oldOption | O_NONBLOCK;
    fcntl( fd, F_SETFL, newOption );
    return oldOption;
}

/*static*/ void addFdToEpoll(int epollFd, int fd) {
    epoll_event epollEvent{};
    epollEvent.data.fd = fd;
    epollEvent.events = EPOLLIN | EPOLLET;
    setFdNonblocking( fd );
    epoll_ctl( epollFd, EPOLL_CTL_ADD, fd, &epollEvent );
}

/*static*/ void addSignal(int sig, void (* signalHandler)(int), bool restart) {
    struct sigaction sigAction{};
    sigAction.sa_handler = signalHandler;
    if (restart) {
        sigAction.sa_flags |= SA_RESTART;
    }
    sigfillset( &sigAction.sa_mask );
    sigaction( sig, &sigAction, nullptr );
    // 判断。
}

/*static*/ void signalHandler(int sig) {
    int saveErrno = errno;
    send( signalPipeFd[1], (char*) &sig, 1, 0 );
    errno = saveErrno;
}

/*static*/ void removeFd(int epollFd, int fd) {
    epoll_ctl( epollFd, EPOLL_CTL_DEL, fd, 0 );
    close( fd );
}
